package com.example.service.impl;

import com.example.entity.User;
import com.example.mapper.UserDao;
import com.example.service.SubUserService;
import com.example.service.UserService;
import com.example.spring.aopbug.Metrics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2022-07-15 18:02:02
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Autowired
    private SubUserService subUserService;

    /**
     * 新增数据
     *
     * @return 实例对象
     * 异常无法传播出方法，导致事务无法回滚, 如果希望自己捕获异常进行处理的话，可以手动设置回滚
     */
    @Override
    @Transactional
    public User insert(String name) {
        User user = new User();
        user.setId(100);
        user.setName(name);
        userDao.insert(user);
        if (name.equals("test")) {
            throw new RuntimeException("error");
        }
        return null;
    }

    /**
     * 事务默认只回滚非检查性异常，如果想回滚检查性异常 可以指定rollbackfor为Exception 来设置任何异常都可以回滚
     *
     * @param name
     * @throws IOException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createUserWrong2(String name) throws IOException {
        User user = new User();
        user.setId(100);
        user.setName(name);
        userDao.insert(user);
        otherTask();
    }

    //因为文件不存在，一定会抛出一个IOException
    private void otherTask() throws IOException {
        Files.readAllLines(Paths.get("file-that-not-exist"));
    }

    @Override
    @Transactional
    public void insertMainSubUser(String name) {
        User mainUser = new User();
        mainUser.setId(100);
        mainUser.setName("父:" + name);
        User subUser = new User();
        subUser.setId(100);
        subUser.setName("子：" + name);

        createMainUser(mainUser);

        try {
            subUserService.createSubUser(subUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void createMainUser(User user) {
        userDao.insert(user);
    }


}
